package com.shuoyue.adven.main.bussiness;

import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.yf_rk3288_api.YF_RK3288_API_Manager;
import com.shuoyue.adven.CommonUtil;
import com.shuoyue.adven.R;
import com.shuoyue.adven.entity.AppVersionInfo;
import com.shuoyue.adven.entity.PowerTimePlan;
import com.shuoyue.adven.init.RegistActivity;
import com.shuoyue.adven.init.VersionContract;
import com.shuoyue.adven.main.appcontrol.PowerUtil;
import com.sm.appbase.base.basemvp.BaseMvpActivity;

import java.io.File;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import startest.ys.com.poweronoff.PowerOnOffManager;

public class MainFragmentActivity extends BaseMvpActivity implements VersionContract.View {
    @BindView(R.id.lay_propery_adv)
    FrameLayout lay_propery_adv;

    //    @BindView(R.id.page_title)
//    TextView pageTitle;
    YF_RK3288_API_Manager yfapi;
    VersionContract.Presenter presenter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main_fragment_three_area;
    }

    @Override
    protected void initView() {
        int width = CommonUtil.getScreenWidth(mContext);
        int heght = width / 16 * 9;
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, heght);
        lay_propery_adv.setLayoutParams(layoutParams);
        //清除电源计划
        Intent intent = new Intent("android.intent.ClearOnOffTime");
        this.mContext.sendBroadcast(intent);
        String powerOn = PowerOnOffManager.getInstance(mContext).getLastestPowerOnTime();
        String powerOff = PowerOnOffManager.getInstance(mContext).getPowerOffTime();

        Log.e("gggggggg", powerOff);
        Log.e("gggggggg", powerOn);

    }

    /**
     * @param afterMinOff 几分钟后关机
     * @param afterOffOn  关机后几分钟开机
     */
    private void setPowerTask(int afterMinOff, int afterOffOn) {
        final Calendar mCalendar = Calendar.getInstance();
        int mYearOff, mMonthOff, mDayOff, mHourOff, mMinuteOff;
        int mYearOn, mMonthOn, mDayOn, mHourOn, mMinuteOn;

        long time = System.currentTimeMillis();
        mCalendar.setTimeInMillis(time);

        mCalendar.add(Calendar.MINUTE, afterMinOff);
        mYearOff = mCalendar.get(Calendar.YEAR);
        mMonthOff = mCalendar.get(Calendar.MONTH);
        mDayOff = mCalendar.get(Calendar.DAY_OF_MONTH);
        mHourOff = mCalendar.get(Calendar.HOUR_OF_DAY);
        mMinuteOff = mCalendar.get(Calendar.MINUTE);

        mCalendar.add(Calendar.MINUTE, afterOffOn);
        mYearOn = mCalendar.get(Calendar.YEAR);
        mMonthOn = mCalendar.get(Calendar.MONTH);
        mDayOn = mCalendar.get(Calendar.DAY_OF_MONTH);
        mHourOn = mCalendar.get(Calendar.HOUR_OF_DAY);
        mMinuteOn = mCalendar.get(Calendar.MINUTE);


        int[] timeoffArray = {mYearOff, mMonthOff + 1, mDayOff, mHourOff, mMinuteOff};
        int[] timeonArray = {mYearOn, mMonthOn + 1, mDayOn, mHourOn, mMinuteOn};

//        int[] timeoffArray = {mYear, mMonth + 1, mDay, 13, 5};
//        int[] timeonArray = {mYear, mMonth + 1, mDay, 13, 9};

        Toast.makeText(getApplicationContext(), "The manchine will be shutdown at " + timeoffArray[0] + "/" + timeoffArray[1] + "/" + timeoffArray[2] + ":" + timeoffArray[3] + ":" + timeoffArray[4] + "\n" + "reboot at " + timeonArray[0] + "/" + timeonArray[1] + "/" + timeonArray[2] + ":" + timeonArray[3] + ":" + timeonArray[4] + "\n", Toast.LENGTH_LONG).show();
        yfapi.yfsetOnOffTime(timeonArray, timeoffArray, true);

        Log.e("gggggggg", PowerOnOffManager.getInstance(mContext).getPowerOffTime());
        Log.e("gggggggg", PowerOnOffManager.getInstance(mContext).getLastestPowerOnTime());
//        PowerUtil.setPowerOneTime(mContext, timeonArray, timeoffArray);


    }

    @Override
    public void initData() {
        presenter = new VersionContract.Presenter();
        presenter.attachView(this);
        yfapi = new YF_RK3288_API_Manager(this);
        presenter.getVersionInfo();
//        new Handler().postDelayed(this::setPowerTask, 10000);
        new Handler().postDelayed(() -> presenter.getPowerPlan(), 20000);
//        downloadSuc(new File("/storage/emulated/0/Android/data/com.shuoyue.adven/files/apk/mlb.apk"));
    }

    @OnClick(R.id.lay_top)
    public void onViewClicked() {
//        View view = findViewById(R.id.lay_top);
//        Log.e("xxx", view.getHeight() + "");
        startActivity(new Intent(mContext, RegistActivity.class));
    }

    @Override
    public void downloadSuc(File f) {
        runOnUiThread(() -> {
//            final String ACTION_INSTALL_APP = "com.android.lango.installapp";
//            Intent intent = new Intent(ACTION_INSTALL_APP);
//            intent.putExtra("apppath", f.getAbsolutePath());
//            mContext.sendBroadcast(intent);
//
            //静默安装后，会关闭APP，这里延迟4分钟后关机，8分钟后启动
            setPowerTask(4, 4);

            //开始静默安装
            yfapi.yfslientinstallapk(f.getAbsolutePath());
        });

    }

    @Override
    public void getVersion(AppVersionInfo appVersionInfo) {
        if (VersionContract.packageCode(mContext) < appVersionInfo.getVersion()) {
            //更新
            presenter.downloadApk(appVersionInfo.getUrl(),
                    CommonUtil.getDownloadPath() + File.separator + "mlb.apk");
        }
    }

    @Override
    public void progress(int progress) {

    }

    @Override
    public void downloadStart() {

    }

    @Override
    public void downloadError(String msg) {

    }

    @Override
    public void setPowerInfo(List<PowerTimePlan> planList) {
        if (planList == null || planList.size() < 2) {
            //如果出錯了，延遲再次请求每5分钟一次
            new Handler().postDelayed(() -> presenter.getPowerPlan(), 300000);
        } else {
//
            int[] timeoffArray = new int[]{planList.get(0).getYear(),
                    planList.get(0).getMouth(),
                    planList.get(0).getDay(),
                    planList.get(0).getHour(),
                    planList.get(0).getMin()};//下次关机时间
            int[] timeonArray = new int[]{planList.get(1).getYear(),
                    planList.get(1).getMouth(),
                    planList.get(1).getDay(),
                    planList.get(1).getHour(),
                    planList.get(1).getMin()};//下次开机时间
//            int[] timeoffArray = new int[]{2020, 12, 4, 21, 50};//下次关机时间
//            int[] timeonArray = new int[]{2020, 12, 4, 21, 55};//下次开机时间
            PowerUtil.setPowerOneTime(this, timeonArray, timeoffArray);
            yfapi.yfsetOnOffTime(timeonArray, timeoffArray, true);
        }

    }


}
